package com.feinno.module.security.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.feinno.framework.common.web.AbstractController;
import com.feinno.module.security.domain.Menu;
import com.feinno.module.security.domain.Resource;
import com.feinno.module.security.service.MenuService;
import com.feinno.module.security.service.ResourceService;

@Controller
@RequestMapping(value = "/admin/system/resource")
public class ResourceController extends AbstractController<Resource, ResourceService> {

	@Autowired
	ResourceService resourceService;

	@Autowired
	MenuService menuService;

	@Override
	protected void onSave(Resource entity, Model model, HttpServletRequest request, HttpServletResponse response, boolean isCreate) {
		List<String> menulist = new ArrayList<String>();
		if (request.getParameterValues("itemlist") != null && request.getParameterValues("itemlist").length != 0) {
			for (int i = 0; i < request.getParameterValues("itemlist").length; i++) {
				menulist.add(request.getParameterValues("itemlist")[i]);
			}
		}
		for (String menuid : menulist) {
			Menu menu = menuService.get(Long.valueOf(menuid));
			entity.setMenu(menu);
		}
		super.onSave(entity, model, request, response, isCreate);
	}

	@Override
	protected void referenceData(HttpServletRequest request, Map<String, Object> model) {
		try {
			List<Menu> menus = menuService.getAll();
			model.put("menulist", menus);
			request.setAttribute("totalRows", menus.size());
		} catch (Exception e) {
			// ig
		}
	}

	/**
	 * 不自动绑定对象中的roleList属性，另行处理。
	 */
	@InitBinder
	@Override
	public void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields("roleList");
		super.initBinder(binder);
	}	
}
